package cn.rkylin.oms.push.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.ectrade.dao.IEcOrderDAO;
import cn.rkylin.oms.ectrade.vo.EcOrderVO;
import cn.rkylin.oms.push.entity.vip.ShipOrderPackageProduct;
import cn.rkylin.oms.push.entity.vip.ShipOrderRequest;
import cn.rkylin.oms.push.entity.vip.UpdateInventoryRequest;
import cn.rkylin.oms.system.logistics.dao.ILogisticsDAO;
import cn.rkylin.oms.system.logistics.vo.LogisticsVO;
import cn.rkylin.oms.system.shop.domain.Shop;

/**
 * VipPushVisitor
 * 
 * @author qitao
 *
 */
@Service("vipPushVisitor")
public class VipPushVisitor extends PushVisitor {

	// 数据库访问对象
	@Autowired
	private IDataBaseFactory dao;

	@Autowired
	private IEcOrderDAO ecOrderDAO;

	@Autowired
	private ILogisticsDAO ilgstDAO;

	@Autowired
	private LogUtil logUtil;

	@Value("${gateway}")
	private String gateway;

	private final String sessionKey = "sessionKey";

	/**
	 * 系统发货
	 * 
	 * @param shop
	 *            店铺ID
	 * @param ecItemCode
	 *            平台商品编码
	 * @param ecTradeCode
	 *            平台交易单号
	 * @param ecSkuCode
	 *            平台规格编码
	 * @return
	 */
	public Map<String, Object> pushSystemConsignment(Shop shop, String ecItemCode, String ecTradeCode, String ecSkuCode,
			String shipTime) {
		return null;
	}

	/**
	 * 自己联系物流（线下物流）发货
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecTradeCode
	 *            平台交易编码
	 * @param lgstNo
	 *            物流单号
	 * @param lgstCode
	 *            物流公司编码
	 * @return 结果对象
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> pushTradeOfflineSend(Shop shop, String ecTradeCode, String lgstNo, String lgstCode)
			throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		// 快递公司名称
		LogisticsVO lgstVO = new LogisticsVO();
		CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
		if (currUser == null) {
			lgstVO.setPrjId(shop.getPrjId());
		} else {
			lgstVO.setPrjId(currUser.getCurrentProject().getPrjId());
		}
		lgstVO.setLgstCode(lgstCode);
		List<LogisticsVO> lgstList = ilgstDAO.getLgstByCondition(lgstVO);
		String lgstName = "";
		if (lgstList.size() > 0) {
			LogisticsVO lgstData = lgstList.get(0);
			lgstName = lgstData.getLgstName();
		}

		// 发货的订单商品列表
		Map<String, String> ecOrderMap = new HashMap<String, String>();
		ecOrderMap.put("ecTradeCode", ecTradeCode);
		List<EcOrderVO> listOrderDeal = ecOrderDAO.findOrderList("selectOrderByTradeItemSku", ecOrderMap);
		List<ShipOrderPackageProduct> lstShipOrderPackageProduct = new ArrayList<ShipOrderPackageProduct>();
		for (EcOrderVO ecOrderVO : listOrderDeal) {
			ShipOrderPackageProduct shipOrderPackageProduct = new ShipOrderPackageProduct();
			shipOrderPackageProduct.setBarcode(ecOrderVO.getEcSkuCode());
			shipOrderPackageProduct.setAmount(ecOrderVO.getQty().toString());
			lstShipOrderPackageProduct.add(shipOrderPackageProduct);
		}

		// 唯品会平台发货
		ShipOrderRequest shipOrderRequest = new ShipOrderRequest();
		shipOrderRequest.setShopId(shop.getShopId());
		shipOrderRequest.setOrder_id(ecTradeCode);
		shipOrderRequest.setCarrier_code(lgstCode);
		shipOrderRequest.setCarrier_name(lgstName);
		shipOrderRequest.setPackage_type("1");
		shipOrderRequest.setTransport_no(lgstNo);
		shipOrderRequest.setLstShipOrderPackageProduct(lstShipOrderPackageProduct);
		String requestParams = JSON.toJSONString(shipOrderRequest);
		String resJson = HttpUtils.sendByPost(gateway + "/microservice-vip/trade/pushShipOrder", requestParams);
		Map<String, String> resultMap = JSON.parseObject(resJson, Map.class);

		// 记录日志
		logUtil.info(new DBLog(ecTradeCode, "vipapis.delivery.DvdDeliveryService -> ship", "pushTradeOfflineSend",
				"[" + requestParams + "," + resultMap.get("msg") + "]"));

		if ("true".equals(resultMap.get("success"))) {
			returnMap.put("success", "y");
			returnMap.put("msg", "");
		} else {
			returnMap.put("success", "n");
			returnMap.put("msg", resultMap.get("msg"));
		}

		return returnMap;
	}

	/**
	 * 商品上架
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecItemCode
	 *            平台商品编码
	 * @param stockCount
	 *            库存数量
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushItemListing(Shop shop, String ecItemCode, String stockCount) {
		return null;
	}

	/**
	 * 商品下架
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecItemCode
	 *            平台商品编码
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushItemDeListing(Shop shop, String ecItemCode) {
		return null;
	}

	/**
	 * 批量同意退款
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecRefundCodes
	 *            平台退款编号, 按照 ","号分割
	 * @param code
	 *            短信验证码
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushRefundBatchAgree(Shop shop, String ecRefundCodes, String code) {
		return null;
	}

	/**
	 * 拒绝退款
	 * 
	 * @param shop
	 * @param ecRefundCode
	 *            退款单号
	 * @param refuseMessage
	 *            拒绝退款时的说明信息，长度2-200
	 * @param refuseReasonId
	 *            拒绝原因编号，会提供用户拒绝原因列表供选择
	 * @param refusePath
	 *            拒绝退款时的退款凭证对应的本地绝对路径，一般是卖家拒绝退款时使用的发货凭证，最大长度130000字节，支持的图片格式： GIF,
	 *            JPG, PNG支持的文件类型：gif,jpg,png
	 * @return
	 */
	@Override
	public Map<String, Object> pushRefundRefuse(Shop shop, String ecRefundCode, String refuseMessage,
			String refuseReasonId, String refusePath) {
		return null;
	}

	/**
	 * 卖家同意退货
	 * 
	 * @param shop
	 * @param ecRefundCode
	 *            退款单编号
	 * @param name
	 *            卖家姓名，淘宝退款为必填项。
	 * @param address
	 *            卖家提供的退货地址，淘宝退款为必填项。
	 * @param post
	 *            卖家提供的退货地址的邮编，淘宝退款为必填项
	 * @param tel
	 *            卖家座机，淘宝退款为必填项。
	 * @param mobile
	 *            卖家手机，淘宝退款为必填项。
	 * @param remark
	 *            卖家退货留言，天猫退款为必填项。
	 * @param sellerAddressId
	 *            卖家收货地址编号，天猫退款为必填项。
	 * @return
	 */
	@Override
	public Map<String, Object> pushReturnGoodsAgree(Shop shop, String ecRefundCode, String name, String address,
			String post, String tel, String mobile, String remark, String sellerAddressId) {
		return null;
	}

	/**
	 * 审核退款单
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecRefundCode
	 *            平台退款编号
	 * @param erpStatus
	 *            审核状态 已审核/未审核
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushRefundAppr(Shop shop, String ecRefundCode, String erpStatus) {
		return null;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> pushItemQuantityUpdate(Shop shop, String ecItemCode, String skuId, String stockCount) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			// 唯品会库存推送
			UpdateInventoryRequest updateInventoryRequest = new UpdateInventoryRequest();
			updateInventoryRequest.setShopId(shop.getShopId());
			updateInventoryRequest.setBarcode(ecItemCode);
			updateInventoryRequest.setQuantity(Integer.valueOf(stockCount));
			updateInventoryRequest.setBatch_no(java.util.UUID.randomUUID().toString().replace("-", ""));
			updateInventoryRequest.setSync_mode(0);
			String requestParams = JSON.toJSONString(updateInventoryRequest);
			String resJson = HttpUtils.sendByPost(gateway + "/microservice-vip/item/pushUpdateInventory", requestParams);
			Map<String, String> resultMap = JSON.parseObject(resJson, Map.class);

			// 记录日志
			logUtil.info(new DBLog(ecItemCode, "vipapis.inventory.InventoryService -> updateInventory",
					"pushItemQuantityUpdate", "[" + requestParams + "," + resultMap.get("msg") + "]"));

			if ("true".equals(resultMap.get("success"))) {
				returnMap.put("success", "y");
				returnMap.put("msg", "");
			} else {
				returnMap.put("success", "n");
				returnMap.put("msg", resultMap.get("msg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put("success", "n");
			returnMap.put("msg", e.getMessage());
		}

		return returnMap;
	}

	@Override
	public Map<String, Object> pushSkuQuantityUpdate(Shop shop, String ecItemCode, String ecSkuCode,
			String stockCount) {
		return null;
	}

	/**
	 * 修改一笔交易备注
	 */
	public Map<String, Object> pushTradeMemo(Shop shop, Long tid, String memo, Long flag) throws Exception {
		return null;
	}

}
